package com.qcxk.yuqian.system.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qcxk.yuqian.rtu.entity.Files;
import com.qcxk.yuqian.rtu.service.IFilesService;
import com.qcxk.yuqian.system.component.behaviour.BehaviourOperator;
import com.qcxk.yuqian.system.component.constant.SystemConstant;
import com.qcxk.yuqian.system.component.token.admin.AdminTokenProccessor;
import com.qcxk.yuqian.system.component.token.front.FrontTokenProccessor;
import com.qcxk.yuqian.system.entity.*;
import com.qcxk.yuqian.system.mapper.RoleMapper;
import com.qcxk.yuqian.system.mapper.UserRoleMapper;
import com.qcxk.yuqian.system.service.AuthService;
import com.qcxk.yuqian.system.service.DictionaryService;
import com.qcxk.yuqian.system.service.IUserauthorderService;
import com.qcxk.yuqian.system.service.UserService;
import com.qcxk.yuqian.system.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

//import com.aliyun.dysmsapi20170525.models.SendSmsResponse;

@Slf4j
@RestController
public class SystemController {
    @Value("${spring.servlet.uploadPath}")
    private String uploadPath;
    @Value("${spring.servlet.server.name}")
    private String serverNAME;
    @Value("${spring.servlet.server.port}")
    private String serverPORT;
    @Value("${validateCode.send}")
    private String send;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private IFilesService filesService;
    @Autowired
    private MailUtil mailUtil;

    @Autowired
    private UserService userService;

    @Autowired
    private IUserauthorderService userauthorderService;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private AuthService authService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private DictionaryService dictionaryService;
    @Autowired
    private AdminTokenProccessor adminTokenProccessor;
    @Autowired
    private FrontTokenProccessor frontTokenProccessor;
    //超时时间
    @Value("${login.outtime}")
    private Long SYS_LOGIN_TOKEN_OUTTIME;
    @Value("${validateCode.outtime}")
    private Long SYS_VALIDATECODE_OUTTIME;
    @Value("${validateCode.dig}")
    private Integer SYS_VALIDATECODE_DIG;
    //同一个用户只允许在一台设备登录
    @Value("${login.only}")
    public boolean SYS_LOGIN_ONLY;



    @BehaviourOperator(desc = "测试是否登录")
    @RequestMapping(value = "/testUser")
    public JSONObject testUser(String token) {
        JSONObject json = new JSONObject();

        json.put("code", "0");
        return json;
    }

    @BehaviourOperator(desc = "修改热词")
    @RequestMapping(value = "/chgHotwords")
    public JSONObject chgHotwords(String hotwords) {
        JSONObject json = new JSONObject();
        dictionaryService.chgHotwords(hotwords);
        json.put("code", "0");
        return json;
    }

    @BehaviourOperator(desc = "查询热词")
    @RequestMapping(value = "/getHotwords")
    public JSONObject getHotwords() {
        JSONObject json = new JSONObject();
        String hotwords = "";
        QueryWrapper<Dictionary> dictionaryQueryWrapper = new QueryWrapper<>();
        dictionaryQueryWrapper.eq("sign", "hotwords");
        List<Dictionary> dictionaries = dictionaryService.list(dictionaryQueryWrapper);
        if (dictionaries != null && !dictionaries.isEmpty()) {
            List<String> hotwordArr = new ArrayList<>();
            for (Dictionary item : dictionaries) {
                hotwordArr.add(item.getTextCn());
            }
            hotwords = String.join(",", hotwordArr);
            json.put("hotwords", hotwords);
        }
        json.put("code", "0");
        return json;
    }

    @BehaviourOperator(desc = "后台用户二次验证码")
    @RequestMapping(value = "/checkValidateCode")
    public JSONObject checkvalCode(String phone, String validateCode) {
        JSONObject json = new JSONObject();

        if (null != redisUtil.get(phone + "") && validateCode.equals(redisUtil.get(phone + ""))) {
            //登录验证通过
            redisUtil.del(phone + "");
            json.put("code", "0");
        } else {
            //登录验证不通过
            json.put("code", "1");
            json.put("msg", SystemConstant.SYS_LOGIN_VALICODE_ERROR_CN);
        }
        return json;
    }

    @BehaviourOperator(desc = "校验手机号")
    @RequestMapping(value = "/validataPhone")
    public JSONObject validataPhone(String phone, Integer userId) {
        JSONObject json = new JSONObject();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("phone", phone);
        if (userId != null) {
            userQueryWrapper.ne("id", userId);
        }
        User user = userService.getOne(userQueryWrapper);
        if (user != null) {
            json.put("code", "1");
            json.put("msg", SystemConstant.SYS_PHONE_ERROR_CN);
        } else {
            json.put("code", "0");
        }
        return json;
    }

    @BehaviourOperator(desc = "后台用户修改菜单顺序")
    @RequestMapping(value = "/chgMenuOrder")
    public JSONObject chgMenuOrder(String menuListStr) {
        JSONObject json = new JSONObject();
        JSONArray menuList = JSONArray.parseArray(menuListStr);
        if (menuList != null && !menuList.isEmpty()) {
            String userId = (String) redisUtil.get(request.getHeader("token"));
            QueryWrapper<Userauthorder> userauthorderQueryWrapper = new QueryWrapper<>();
            userauthorderQueryWrapper.eq("user_id", userId);
            userauthorderService.remove(userauthorderQueryWrapper);
            for (int i = 0; i < menuList.size(); i++) {
                JSONObject jsonObject = (JSONObject) menuList.get(i);
                Userauthorder userauthorder = new Userauthorder();
                userauthorder.setAuthId(jsonObject.getInteger("id"));
                userauthorder.setUserId(Integer.parseInt(userId));
                userauthorder.setOrderNum(i + 1);
                userauthorder.setOften(jsonObject.getString("often"));
                userauthorderService.save(userauthorder);
            }
            json.put("code", "0");
        } else {
            //不通过
            json.put("code", "1");
            json.put("msg", SystemConstant.SYS_DATABASE_ERROR_CN);
        }

        return json;
    }


    @BehaviourOperator(desc = "后台用户登录")
    @RequestMapping(value = "/loginByAdmin")
    public JSONObject loginByAdmin(String username, String password) {

        JSONObject json = new JSONObject();
        User user = new User();
        user.setUsername(username);
        User data = userService.getOne(new QueryWrapper<>(user));
        if (data == null) {
            json.put("code", "1");
            json.put("msg", SystemConstant.SYS_LOGIN_USERNAMEORPASSWORDERROR_CN);
            return json;
        }
       // String sourcePassword = DigestUtils.sha256Hex(password);
        if (password.equals(data.getPassword())) {
            //用户是否被禁用
            if ("1".equals(data.getState())) {
                //登录验证不通过
                json.put("code", "1");
                json.put("msg", SystemConstant.SYS_USERSTATE_ERROR_CN);
            }
            //登录验证通过
            data.setLastTime(ThmsUtil.getDate("yyyy-MM-dd HH:mm:ss"));
            data.setLastIp(IPUtil.getIpAdrress(request));
            userService.updateById(data);
            //更新缓存
       /*     byte[] b = redisUtil.serializer(data);
            redisUtil.set("user_" + data.getId(), b);*/

            String token = adminTokenProccessor.makeToken();
            //获取用户的权7限
            List<JSONObject> authJSON = authService.queryUserAuthList(data.getId());
            //获取用户按钮id
            List<Auth> btnJSON = authService.getBtnList(data.getId());

            List<String> btnsList = new ArrayList<>();
            for (Auth item : btnJSON) {
                btnsList.add(item.getGrantAuth());
            }
            QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
            userRoleQueryWrapper.eq("user_id", data.getId());
            UserRole userRole = userRoleMapper.selectOne(userRoleQueryWrapper);
            if (userRole == null) {
                //登录验证不通过
                json.put("code", "1");
                json.put("msg", SystemConstant.SYS_QUANXIAN);
                return json;
            }
            JSONObject dataJSON = new JSONObject();
            dataJSON.put("authJSON", authJSON);
            dataJSON.put("btnsList", btnsList);
            json.put("data", dataJSON);
            json.put("code", "0");
            json.put("headpic", data.getHeadpic());
            json.put("token", token);
            json.put("name", data.getFullName());
            Role role = roleMapper.selectById(userRole.getRoleId());
            json.put("roleName", role.getName());
            json.put("dataAccess", role.getDataAccess());
            json.put("phone", data.getPhone());
            json.put("username", data.getUsername());
            json.put("qq", data.getQq());
            json.put("wx", data.getWx());
            json.put("id", data.getId());
            json.put("roleId", userRole.getRoleId());
            json.put("organId", data.getOrganId());
   /*         if (SYS_LOGIN_ONLY) {
                redisUtil.set(data.getId() + "", token, SYS_LOGIN_TOKEN_OUTTIME);
            }
            redisUtil.set(token, data.getId() + "", SYS_LOGIN_TOKEN_OUTTIME);*/
        } else {
            //登录验证不通过
            json.put("code", "1");
            json.put("msg", SystemConstant.SYS_LOGIN_USERNAMEORPASSWORDERROR_CN);

        }
        return json;
    }

    @BehaviourOperator(desc = "校验邮箱地址")
    @RequestMapping(value = "/validataEmail")
    public JSONObject validataEmail(String email) {
        JSONObject json = new JSONObject();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("email", email);
        User user = userService.getOne(userQueryWrapper);
        if (user != null) {
            json.put("code", "1");
            json.put("msg", SystemConstant.SYS_EMAIL_ERROR_CN);
        } else {
            json.put("code", "0");
        }
        return json;
    }

    @BehaviourOperator(desc = "忘记密码")
    @RequestMapping(value = "/lostPWD")
    public JSONObject lostPWD(User user) {
        JSONObject json = new JSONObject();
        user = userService.getOne(new QueryWrapper<User>(user));
        if (user != null) {
            json.put("code", "0");
        } else {
            json.put("code", "1");
            json.put("msg", SystemConstant.SYS_LOSTPWD_ERROR_CN);
        }
        return json;
    }

    @BehaviourOperator(desc = "找回密码")
    @RequestMapping(value = "/resetPWD")
    public JSONObject resetPWD(User user) {
        JSONObject json = new JSONObject();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user.getUsername());
        User item = userService.getOne(queryWrapper);
        item.setPassword(DigestUtils.sha256Hex(user.getPassword()));
        if (userService.updateById(item)) {
            json.put("code", "0");
        } else {
            json.put("code", "1");
            json.put("msg", SystemConstant.SYS_DATABASE_ERROR_CN);
        }
        return json;
    }

    @BehaviourOperator(desc = "后端修改密码")
    @RequestMapping(value = "/modifyPWDForAdmin")
    public JSONObject modifyPWDForAdmin(String oldpass, String newpass) {
        JSONObject json = new JSONObject();
        Integer id = Integer.parseInt((String) redisUtil.get(request.getHeader("token")));

        User item = userService.getById(id);
        if (item.getPassword().equals(oldpass)) {
            item.setPassword(newpass);
            if (userService.updateById(item)) {
                json.put("code", "0");
                //更新缓存
                byte[] b = redisUtil.serializer(item);
                redisUtil.set("user_" + item.getId(), b);
            } else {
                json.put("code", "1");
                json.put("msg", SystemConstant.SYS_DATABASE_ERROR_CN);
            }
        } else {
            json.put("code", "1");
            json.put("msg", SystemConstant.SYS_OLDPASS_ERROR_CN);
        }
        return json;
    }

    @BehaviourOperator(desc = "后端用户退出登录")
    @RequestMapping(value = "/exit")
    public JSONObject exit() {
        JSONObject json = new JSONObject();
      /*  String userId = (String) redisUtil.get(request.getHeader("token"));
        redisUtil.del(request.getHeader("token"));*/
        json.put("code", "0");
        return json;
    }

    @BehaviourOperator(desc = "找回密码时验证用户名并发送验证码")
    @RequestMapping(value = "/chkUserSendValidateCode")
    public JSONObject front_chkUserSendValidateCode(String username) throws Exception {
        JSONObject json = new JSONObject();
        if (StringUtils.isNotBlank(username)) {
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("username", username);
            User user = userService.getOne(userQueryWrapper);
            if (user != null) {
                String phone = user.getPhone();
                if (StringUtils.isNotBlank(phone)) {
                    //生成验证码
                    String vCode = ValidateCodeUtil.getNonce_str(SYS_VALIDATECODE_DIG);
                    redisUtil.set(phone, vCode, SYS_VALIDATECODE_OUTTIME);
                    //发送验证码
                    System.out.println(phone + "验证码是：" + vCode);
//                    if(send.equals("0")){
//                        SendSmsResponse sendSmsResponse = ALIYUNSMSUtil.sendSms(phone,vCode);
//                        log.info("短信发送结果："+sendSmsResponse.getBody().getMessage());
//                    }
                    json.put("code", "0");
                    json.put("phone", phone);
                } else {
                    json.put("code", "1");
                    json.put("msg", SystemConstant.SYS_PHONENOTEX_ERROR_CN);
                }
            } else {
                json.put("code", "1");
                json.put("msg", SystemConstant.SYS_USERNAMENOTEX_ERROR_CN);
            }


        } else {
            json.put("code", "1");
            json.put("msg", SystemConstant.SYS_USERNAMENOTEX_ERROR_CN);
        }


        return json;
    }

    @BehaviourOperator(desc = "前端用户退出登录")
    @RequestMapping(value = "/frontExit")
    public JSONObject frontExit() {
        JSONObject json = new JSONObject();
        redisUtil.del(request.getHeader("token"));
        json.put("code", "0");
        return json;
    }

    //    @BehaviourOperator(desc = "测试发送邮件")
//    @RequestMapping(value = "/sendMail")
//    public JSONObject sendMail(){
//        JSONObject json = new JSONObject();
//        try{
//            mailUtil.testSend();
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        json.put("code","0");
//        return json;
//    }
    @BehaviourOperator(desc = "校验用户名")
    @RequestMapping(value = "/validataUsername")
    public JSONObject validataUsername(String username) {
        JSONObject json = new JSONObject();
        QueryWrapper<User> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq("username", username);
        User user = userService.getOne(usersQueryWrapper);
        if (user != null) {
            json.put("code", "1");
            json.put("msg", SystemConstant.SYS_USERNAME_ERROR_CN);
        } else {
            json.put("code", "0");
        }
        return json;
    }

    @RequestMapping(value = "/uploadFile")
    public JSONObject uploadFile(@RequestParam("file") MultipartFile file[]) throws IllegalStateException, IOException {
        JSONObject json = new JSONObject();
        // 判断文件是否为空，空则返回失败页面
        if (file == null || file.length == 0) {
            json.put("code", "1");
            json.put("msg", "文件不能为空");
            return json;
        }
        List<String> data = new ArrayList<String>();
        // 获取文件存储路径（绝对路径）-已改为从yml文件中获取
        //String path = request.getServletContext().getRealPath("/resources/img");
        List<Files> filesList = new ArrayList<>();
        String userId = (String) redisUtil.get(request.getHeader("token"));

        for (int i = 0; i < file.length; i++) {
            // 获取原文件名
            String fileName = file[i].getOriginalFilename();
            // 创建文件实例
            File filePath = new File(uploadPath, (System.currentTimeMillis() + "") + ValidateCodeUtil.getNonce_str_four() + fileName.substring(fileName.lastIndexOf(".")));
            // 如果文件目录不存在，创建目录
            if (!filePath.getParentFile().exists()) {
                filePath.getParentFile().mkdirs();
                System.out.println("创建目录" + filePath);
            }
            // 写入文件
            file[i].transferTo(filePath);
            String url = serverNAME + ":" + serverPORT + request.getContextPath()
                    + "/img/" + filePath.getName();
            data.add(url);
            Files files = new Files();
            files.setCtime(ThmsUtil.getDate());
            files.setRealName(fileName);
            files.setStorageName(url);
            files.setFileSize("" + file[i].getSize());
            files.setUId(Integer.parseInt(userId));
            filesList.add(files);
        }
        filesService.saveBatch(filesList);
        json.put("code", 0);
        json.put("data", filesList);
        return json;
    }
/*    public static void main(String[] args ){
       System.out.println(DigestUtils.sha256Hex("123456"));
    }*/
}
